<template>
  <div class="chat-container">
    <div class="chat-header">
      <div class="header-title">
        <i class="el-icon-headset"></i>
        <span>客服工作台</span>
      </div>
      <div class="header-info">
        <span class="status-badge" :class="{ 'online': isConnected }">
          <i class="el-icon-circle-check"></i>
          {{ isConnected ? '在线' : '离线' }}
        </span>
      </div>
    </div>
    <div class="chat-content">
      <div class="user-list">
        <div class="list-header">
          <i class="el-icon-user"></i>
          <span>当前用户</span>
        </div>
        <div class="current-user">
          <div class="user-avatar">{{ userId.charAt(0) }}</div>
          <div class="user-info">
            <div class="user-name">{{ userId }}</div>
            <div class="user-status">正在对话</div>
          </div>
        </div>
      </div>
      <div class="chat-main">
        <div class="chat-box" ref="chatBox">
          <div class="chat-date">{{ currentDate }}</div>
          <div v-for="(msg, index) in messages" 
               :key="index" 
               :class="{'my-message': msg.sender === platformId, 'other-message': msg.sender !== platformId}">
            <div class="message-wrapper">
              <div class="avatar" :class="{'my-avatar': msg.sender === platformId}">
                {{ msg.sender === platformId ? '客服' : msg.sender.charAt(0) }}
              </div>
              <div class="message-content">
                <div class="message-info">
                  <span class="sender-name">{{ msg.sender === platformId ? '客服' : msg.sender }}</span>
                  <span class="message-time">{{ getCurrentTime() }}</span>
                </div>
                <div class="message-bubble">
                  {{ msg.content }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="chat-input">
          <div class="input-toolbar">
            <i class="el-icon-picture-outline"></i>
            <i class="el-icon-folder-opened"></i>
          </div>
          <div class="input-main">
            <input 
              v-model="message" 
              @keyup.enter="sendMessage" 
              placeholder="输入消息..." 
            />
            <el-button 
              type="primary" 
              icon="el-icon-s-promotion" 
              :disabled="!message.trim()"
              @click="sendMessage">
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      socket: null,
      messages: [],
      message: "",
      platformId: "platform",
      userId: "user123",
      isConnected: false,
      currentDate: new Date().toLocaleDateString()
    };
  },
  mounted() {
    this.socket = new WebSocket("ws://localhost:9081/websocket");

    this.socket.onopen = () => {
      console.log("WebSocket 连接成功");
      this.isConnected = true;
      this.socket.send(JSON.stringify({ type: "register", sender: this.platformId }));
    };

    this.socket.onmessage = (event) => {
      try {
        let msg = event.data;
        if (typeof msg === 'string') {
          try {
            msg = JSON.parse(msg);
          } catch (e) {
            const [sender, content] = msg.split(': ');
            msg = {
              type: 'chat',
              sender: sender,
              content: content || msg
            };
          }
        }
        this.messages.push(msg);
        this.scrollToBottom();
      } catch (error) {
        console.error('消息处理错误：', error);
        this.messages.push({
          type: 'system',
          sender: 'System',
          content: event.data
        });
      }
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket 错误：', error);
      this.isConnected = false;
      this.$message.error('连接发生错误');
    };

    this.socket.onclose = () => {
      console.log('WebSocket 连接关闭');
      this.isConnected = false;
      this.$message.warning('连接已关闭');
    };
  },
  methods: {
    sendMessage() {
      if (this.message.trim() === "") return;

      const chatMessage = {
        type: "chat",
        sender: this.platformId,
        receiver: this.userId,
        content: this.message
      };

      this.socket.send(JSON.stringify(chatMessage));
      this.messages.push(chatMessage);
      this.message = "";
      this.scrollToBottom();
    },
    getCurrentTime() {
      const now = new Date();
      return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const chatBox = this.$refs.chatBox;
        chatBox.scrollTop = chatBox.scrollHeight;
      });
    }
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 40px);
  margin: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #2d3a4b;
  color: white;
  border-radius: 12px 12px 0 0;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 500;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-badge {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 12px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.1);
  font-size: 14px;
}

.status-badge.online {
  background: #67C23A;
}

.chat-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.user-list {
  width: 240px;
  border-right: 1px solid #ebeef5;
  background: #f8f9fa;
}

.list-header {
  padding: 16px;
  font-size: 16px;
  font-weight: 500;
  color: #606266;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  gap: 8px;
}

.current-user {
  display: flex;
  align-items: center;
  padding: 16px;
  gap: 12px;
  border-bottom: 1px solid #ebeef5;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.user-status {
  font-size: 12px;
  color: #67C23A;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #fff;
}

.chat-date {
  text-align: center;
  margin: 10px 0;
  color: #909399;
  font-size: 12px;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  margin: 16px 0;
  animation: fadeIn 0.3s ease;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  flex-shrink: 0;
}

.my-avatar {
  background: #67C23A;
}

.message-content {
  margin: 0 12px;
  max-width: 70%;
}

.message-info {
  margin-bottom: 4px;
}

.sender-name {
  font-size: 13px;
  color: #606266;
  margin-right: 8px;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 12px;
  background: #f4f4f5;
  color: #303133;
  font-size: 14px;
  line-height: 1.5;
  word-break: break-word;
}

.my-message .message-wrapper {
  flex-direction: row-reverse;
}

.my-message .message-content {
  align-items: flex-end;
}

.my-message .message-info {
  text-align: right;
}

.my-message .message-bubble {
  background: #409EFF;
  color: white;
}

.chat-input {
  border-top: 1px solid #ebeef5;
  padding: 16px;
}

.input-toolbar {
  padding: 8px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 12px;
}

.input-toolbar i {
  font-size: 20px;
  color: #606266;
  margin-right: 16px;
  cursor: pointer;
}

.input-toolbar i:hover {
  color: #409EFF;
}

.input-main {
  display: flex;
  gap: 12px;
}

input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

input:focus {
  border-color: #409EFF;
  outline: none;
}

.el-button {
  padding: 12px 20px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
